package org.dreamfly.core.action;

import org.apache.struts2.ServletActionContext;
import org.dreamfly.core.bean.*;
import org.dreamfly.core.page.PageInfo;
import org.dreamfly.core.page.PageResultSet;
import org.dreamfly.core.remote.ServiceRepository;
import org.dreamfly.core.remote.exception.ServiceException;
import org.dreamfly.core.service.VideoService;
import org.dreamfly.core.service.VideoTypeService;
import org.dreamfly.core.util.UrlGetter;
import org.dreamfly.core.util.XMLReader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class VideoAction extends BaseAction {
    private SzVideo video;
    private SzVideo object;
    private VideoService videoService;
    private VideoTypeService videoTypeService;
    private List<SzVideo> videos = new ArrayList<SzVideo>();
    private List<SzVideoType> types;
    private List<Long> szTypeIds;
    private List<Long> deleteIds;
    private PageResultSet<SzVideo> resultSet;
    private PageResultSet<SzTempVideo> szTempVideosResultSet;
    private String fileName;
    public static final String uploadFolder = "/upload";
    private String title;
    private String actionName;
    private Long id;
    private String server;
    private String serverName;
    private String isAdmin;
    private String note;
    private String videoUrl;
    private String searchId;
    private String clientPage = "1";
    private String width;
    private String height;
    private ServiceRepository serviceRepository;
    private VideoService videoHessianProxy;
    private List<SzTempVideo> tempList;
    private ResultSetPool resultSetPool;
    private BootUpRegister bootUpRegister;
    private UrlGetter urlGetter;
    /**
     * 分页参数
     * pageSize 每页的大小
     * page     显示的页码
     */
    private Long pageSize = 5L;
    private Long page = 1L;

    /**
     * 删除视频
     *
     * @return success
     */
    public String deleteVideo() {
        videoService.deleteVideo(id);
        return SUCCESS;
    }

    public String deleteVideoList() {
        for (Long id : deleteIds) {
            videoService.deleteVideo(id);
        }
        return SUCCESS;
    }

    /**
     * 修改视频
     *
     * @return
     */
    public String modifyVideoInfo() throws IOException {
        SzVideo temp = new SzVideo();
        temp.setServer(server);
        temp.setId(id);
        temp.setTitle(title);
        temp.setNote(note);
        videoService.addVideoInfo(temp);
        getResponse().getWriter().print("success");
        return null;
    }

    /**
     * 在线播放视频
     */
    public String showVideo() {
        video = videoService.findDetail(video.getId());
        ServerIpInfo ipInfo = resultSetPool.getIpInfo(video.getServer());
        String url = ipInfo.getIp() + ":" + ipInfo.getPort() + videoUrl;

        video.setVideoUrl(url);
        width = video.getDisrate().split("\\*")[0];
        height = video.getDisrate().split("\\*")[1];
        return SUCCESS;
    }


    /**
     * 添加视频信息
     *
     * @return
     */
    public String addVideoInfo() throws IOException {

        SzVideo v = new SzVideo();
        v.setId(id);
        v.setTitle(title);
        v.setServer(server);
        v.setNote(note);

//		VideoInfo.ByReference videoInfo = new VideoInfo.ByReference();
//		System.out.println(2);
//		videoInfo.pcFileType = "avs";
//		videoInfo.pcFilmType = "视频";
//		String videoDir = ServletActionContext.getServletContext().getRealPath(uploadFolder+fileName);
//		videoInfo.pcFilePath = videoDir;
//		videoInfo.pcSeverName = server;
//		videoInfo.pcKeyFrameName = fileName;
//		String videoMinDir = videoDir+"\\min\\";
//		System.out.println("videoMinDir:"+videoMinDir);
//		if(!new File(videoMinDir).exists()){
//			new File(videoMinDir).mkdir();
//		}
//		videoInfo.pcKeyFrameFolder = videoMinDir;
//		videoInfo.iFileID = Integer.parseInt(String.valueOf(id));
//		ContentDll.INSTANCE.Input_data(videoInfo, true);
        videoService.addVideoInfo(v);
        getResponse().getWriter().print("success");
        return null;
    }

    public String getVideoInfo() {
        object = videoService.findDetail(id);
        actionName = "modifyVideo";
        return null != object ? SUCCESS : INPUT;
    }
    /**
     * 按关键字搜索视频
     * @return success
     */
    /*public String searchVideo(){
    if(video==null){
       video = new SzVideo();
       video.setTitle("%");
    }
    *//*try {
			video.setTitle(new String(video.getTitle().getBytes("ISO-8859-1"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }*//*
        actionName="videoNameSearch";
        if(isAdmin==null){
        	resultSet = videoService.normalSearch(video, pageSize, page, null);
        }else{
        	resultSet = videoService.normalSearch(video, pageSize, page, server);
        }
		if(resultSet.getList()==null){
			return "error";
		}
		return SUCCESS;
	}*/


    /**
     * 按关键字搜索指定类型的视频
     *
     * @return success
     */
    public String searchVideoByType() {
        if (video == null) {
            video = new SzVideo();
            video.setTitle("%");
        }
        if ("".equals(video.getTitle())) {
            video.setTitle("%");
        }
        /*try {
			video.setTitle(new String(video.getTitle().getBytes("ISO-8859-1"),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }*/
        if (isAdmin == null) {
            resultSet = videoService.normalSearchByType(video, szTypeIds, pageSize, page, null);
            resultSet.setActionName("videoNameSearch");
        } else {
            resultSet = videoService.normalSearchByType(video, szTypeIds, 15l, page, server);
            resultSet.setActionName("bgVideo");
        }
        resultSet.setType("Video");
        if (resultSet.getList() == null || 0 == resultSet.getList().size()) {
            return INPUT;
        }

        resultSet.setKeyWords(video.getTitle());

        return SUCCESS;
    }

    /**
     * 按内容搜索视频
     *
     * @param
     */
    public String contentSearch() {
        /*
           * try { fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
           * } catch (UnsupportedEncodingException e) { e.printStackTrace(); //To
           * change body of catch statement use File | Settings | File Templates.
           * }
           */
        String videoDir = uploadFolder + fileName;
        List<RemoteServiceInfo> infoList = XMLReader.readServerInfo(ServletActionContext.getServletContext().getRealPath("WEB-INF/video.xml"));
        int serviceNum = infoList.size(); // 远程服务和本地服务的数量和
        // 判断是不是第一次查询
        if (searchId == null) {
            searchId = String.valueOf(Math.random());
            tempList = videoService.contentSearch(videoDir, pageSize, page);
            if (tempList == null) {
                tempList = new ArrayList<SzTempVideo>();
            }
            /**
             * 远程service
             */

            Long maxCount = videoService.findCount(videoDir); // 最多的记录数
            Long totalRow = videoService.findCount(videoDir);
            /**
             * 初始化List
             */
            for (int i = 0; i < serviceNum; i++) {
                try {
                    videoHessianProxy = (VideoService) serviceRepository.getService(VideoService.class, "video_"
                            + String.valueOf(i));
                } catch (ServiceException e) {
                    e.printStackTrace();
                    bootUpRegister.initService();
                    try {
                        videoHessianProxy = (VideoService) serviceRepository
                                .getService(VideoService.class, "video_"
                                        + String.valueOf(i));
                    } catch (ServiceException e1) {
                        e1.printStackTrace();
                    }
                }
                List<SzTempVideo> list = videoHessianProxy.contentSearch(
                        videoDir, pageSize, page);
                if (list != null) {
                    tempList.addAll(list);
                }
                list = null;
                //serviceNum++;
            }
            szTempVideosResultSet = new PageResultSet<SzTempVideo>();
            szTempVideosResultSet.setList(tempList);

            /**
             * 初始化PageInfo
             */
            PageInfo pageInfo = new PageInfo(totalRow, pageSize);
            pageInfo.setClientPage(Long.parseLong(clientPage));
            pageInfo.setMaxQueryTimes(maxCount % pageSize == 0 ? maxCount / pageSize : maxCount / pageSize + 1);
            szTempVideosResultSet.setPageInfo(pageInfo);
            resultSetPool.createResultSet(request.getSession().getId(), searchId, szTempVideosResultSet);
        }//判断需不需要再查询
        else {
            szTempVideosResultSet = resultSetPool.getResultSet(request.getSession().getId(), searchId);
            szTempVideosResultSet.getPageInfo().setClientPage(Long.parseLong(clientPage));
            szTempVideosResultSet.getPageInfo().setCurrentPage(Long.parseLong(clientPage));
            if (szTempVideosResultSet.needQueryDB()) {

                /*try {
                    picture.setTitle(new String(picture.getTitle().getBytes("ISO-8859-1"),"UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }*/
                while (szTempVideosResultSet.needQueryDB()) {
                    PageInfo pageInfo = resultSetPool.getResultSet(request.getSession().getId(), searchId).getPageInfo();
                    if (pageInfo.getMaxQueryTimes().equals(pageInfo.getQueryTime())) {
                        break;
                    }
                    Long page = pageInfo.getQueryTime() + 1L;
                    tempList = videoService.contentSearch(videoDir, pageInfo.getPageSize(), page);
                    if (tempList == null) {
                        tempList = new ArrayList<SzTempVideo>();
                    }
                    resultSetPool.getResultSet(request.getSession().getId(), searchId).getList().addAll(tempList);

                    /**
                     * 远程service
                     */

                    /**
                     * 增加List
                     */
                    for (int i = 0; i < serviceNum; i++) {
                        try {
                            videoHessianProxy = (VideoService) serviceRepository.getService(VideoService.class, "video_" + String.valueOf(i));

                        } catch (ServiceException e) {
                            e.printStackTrace();
                            bootUpRegister.initService();
                            try {
                                videoHessianProxy = (VideoService) serviceRepository
                                        .getService(VideoService.class, "video_"
                                                + String.valueOf(i));
                            } catch (ServiceException e1) {
                                e1.printStackTrace();
                            }
                        }
                        tempList = videoHessianProxy.contentSearch(videoDir, pageInfo.getPageSize(), pageInfo.getQueryTime() + 1L);
                        if (tempList != null) {
                            resultSetPool.getResultSet(request.getSession().getId(), searchId).getList().addAll(tempList);
                        }
                        tempList = null;
                        //serviceNum++;
                    }

                    /**
                     * 修改PageInfo
                     */
                    pageInfo.setClientPage(Long.parseLong(clientPage));
                    pageInfo.setCurrentPage(Long.parseLong(clientPage));
                    pageInfo.setQueryTime(pageInfo.getQueryTime() + 1L);
                    resultSetPool.getResultSet(request.getSession().getId(), searchId).setPageInfo(pageInfo);
                    szTempVideosResultSet = resultSetPool.getResultSet(request.getSession().getId(), searchId);
                }
            }
        }

        List<SzTempVideo> tempVideoList = szTempVideosResultSet.getList();
        translateVideoUrl(tempVideoList);
        szTempVideosResultSet.setList(tempVideoList);
        szTempVideosResultSet = resultSetPool.getResultSet(request.getSession().getId(), searchId);
        szTempVideosResultSet.setKeyWords(fileName);
        szTempVideosResultSet.setActionName("videoContentSearch");
        szTempVideosResultSet.setType("Video");
        if (szTempVideosResultSet.getList() == null || 0 == szTempVideosResultSet.getList().size()) {
            return INPUT;
        }
        return SUCCESS;
    }

    /**
     * @return
     */
    public String videoType() {
        types = videoTypeService.findAll();
        return SUCCESS;
    }

    private void translateVideoUrl(List<SzTempVideo> videoList){
        for(SzTempVideo video : videoList){
            if(!urlGetter.isNeedTranslate(video.getMinPictureUrl())){
            video.setMinPictureUrl(urlGetter.getRemoteUrl(video.getMinPictureUrl(), video.getSzVideo().getServer()));
            }
        }
    }

    public String getVideoUrl() {
        return videoUrl;
    }

    public SzVideo getObject() {
        return object;
    }

    public String getAdmin() {
        return isAdmin;
    }

    public void setAdmin(String admin) {
        isAdmin = admin;
    }

    public void setVideoUrl(String videoUrl) {
        this.videoUrl = videoUrl;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getServer() {
        return server;
    }

    public void setServer(String server) {
        this.server = server;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public SzVideo getVideo() {
        return video;
    }

    public void setVideo(SzVideo video) {
        this.video = video;
    }

    public VideoService getVideoService() {
        return videoService;
    }

    public void setVideoService(VideoService videoService) {
        this.videoService = videoService;
    }

    public List<SzVideo> getVideos() {
        return videos;
    }

    public void setVideos(List<SzVideo> videos) {
        this.videos = videos;
    }

    public List<Long> getSzTypeIds() {
        return szTypeIds;
    }

    public String getActionName() {
        return actionName;
    }

    public void setSzTypeIds(List<Long> szTypeIds) {
        this.szTypeIds = szTypeIds;
    }

    public PageResultSet<SzVideo> getResultSet() {
        return resultSet;
    }

    public void setDeleteIds(List<Long> deleteIds) {
        this.deleteIds = deleteIds;
    }

    public void setResultSet(PageResultSet<SzVideo> resultSet) {
        this.resultSet = resultSet;
    }

    public PageResultSet<SzTempVideo> getSzTempVideosResultSet() {
        return szTempVideosResultSet;
    }

    public void setSzTempVideosResultSet(
            PageResultSet<SzTempVideo> szTempVideosResultSet) {
        this.szTempVideosResultSet = szTempVideosResultSet;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public Long getPageSize() {
        return pageSize;
    }

    public void setPageSize(Long pageSize) {
        this.pageSize = pageSize;
    }

    public Long getPage() {
        return page;
    }

    public void setPage(Long page) {
        this.page = page;
    }

    public VideoTypeService getVideoTypeService() {
        return videoTypeService;
    }

    public void setVideoTypeService(VideoTypeService videoTypeService) {
        this.videoTypeService = videoTypeService;
    }

    public List<SzVideoType> getTypes() {
        return types;
    }

    public void setTypes(List<SzVideoType> types) {
        this.types = types;
    }

    public String getSearchId() {
        return searchId;
    }

    public void setSearchId(String searchId) {
        this.searchId = searchId;
    }

    public String getClientPage() {
        return clientPage;
    }

    public void setClientPage(String clientPage) {
        this.clientPage = clientPage;
    }

    public void setServiceRepository(ServiceRepository serviceRepository) {
        this.serviceRepository = serviceRepository;
    }

    public ResultSetPool getResultSetPool() {
        return resultSetPool;
    }

    public void setResultSetPool(ResultSetPool resultSetPool) {
        this.resultSetPool = resultSetPool;
    }

    public void setVideoHessianProxy(VideoService videoHessianProxy) {
        this.videoHessianProxy = videoHessianProxy;
    }

    public String getIsAdmin() {
        return isAdmin;
    }

    public void setIsAdmin(String isAdmin) {
        this.isAdmin = isAdmin;
    }

    public void setBootUpRegister(BootUpRegister bootUpRegister) {
        this.bootUpRegister = bootUpRegister;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public String getWidth() {
        return width;
    }

    public String getHeight() {
        return height;
    }

    public void setUrlGetter(UrlGetter urlGetter) {
        this.urlGetter = urlGetter;
    }
}
